<template>
  <div ref="chart" class="chart" :style="style"></div>
</template>

<script setup>
import { ref, reactive, watch, nextTick, getCurrentInstance, toRefs, toRaw } from "vue";

// 接收值
const props = defineProps({
  options: {
    type: Object,
    default: () => {},
  },
});
const { options } = toRefs(props);

// 定义值
const chart = ref();
const style = reactive({
  width: "100%",
  height: "320px",
  // background: "#f8f8f8",
  borderRadius: "8px",
});

const instance = getCurrentInstance();
const echarts = instance?.appContext.config.globalProperties.$echarts;

const optionList = reactive({
  title: {
    text: "",
  },
  color: ["#3487FF"],
  // backgroundColor: "#FFFFFF",
  tooltip: {
    trigger: "axis",
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true,
  },
  xAxis: [
    {
      type: "category",
      axisLabel: { interval: 0 },
      splitLine: { show: false },
      data: [],
    },
  ],
  yAxis: {
    type: "value",
    name: "单位：个",
  },
  series: [
    {
      name: "Direct",
      type: "bar",
      barWidth: "60%",
      label: {
        show: true,
        position: "top",
      },
      data: [],
    },
  ],
});

// 定义加载函数
const initCharts = () => {
  if (!options.value) return;
  optionList.xAxis[0].data = options.value.xAxisData;
  if (options.value.axisLabel) {
    optionList.xAxis[0].axisLabel = options.value.axisLabel;
  }
  optionList.series[0].data = options.value.yAxisData;
  optionList.yAxis.name = options.value.yAxisName;
  optionList.series[0].name = options.value.seriesName;

  optionList.title.text = options.value.title;
  let myChart = echarts.init(chart.value);
  myChart.setOption(optionList);
  // window.addEventListener("resize", () => {
  //   myChart.resize();
  // });
};

// 监听当配置项发生变化的时候，调用加载函数
// 监听当配置项发生变化的时候，调用加载函数
watch(
  () => props.options,
  (val) => {
    nextTick(() => {
      initCharts();
    });
  }
);

let myChart;
let resizeHandler = () => {
  if (myChart) {
    myChart.resize();
  }
};

onMounted(() => {
  initCharts();
  window.addEventListener("resize", resizeHandler);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", resizeHandler);
});
</script>

<style lang="scss" scoped>
.chart {
  background-color: var(--base-color);
}
</style>
